package com.example.uploadminio.service;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ProgressInputStream extends FilterInputStream {
    private final long totalBytes;
    private long bytesRead = 0;
    private final UploadProgressListener listener;

    protected ProgressInputStream(InputStream in, long totalBytes, UploadProgressListener listener) {
        super(in);
        this.totalBytes = totalBytes;
        this.listener = listener;
    }

    @Override
    public int read() throws IOException {
        int b = super.read();
        if (b != -1) reportProgress(1);
        return b;
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int n = super.read(b, off, len);
        if (n > 0) reportProgress(n);
        return n;
    }

    private void reportProgress(int n) {
        bytesRead += n;
        if (listener != null) listener.onProgress(bytesRead, totalBytes);
    }
}
